package com.xinsoft.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.ScmPurchaseDto;
import com.xinsoft.entity.dto.ScmPurchaseItemParam;
import com.xinsoft.entity.dto.ScmPurchasePageParam;
import com.xinsoft.entity.dto.ScmPurchasePlanItemParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.*;
import com.xinsoft.service.*;
import com.xinsoft.mapper.ScmPurchaseMapper;
import com.xinsoft.utils.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 13370
* @description 针对表【scm_purchase(采购订单)】的数据库操作Service实现
* @createDate 2023-07-04 14:35:53
*/
@Service
public class ScmPurchaseServiceImpl extends ServiceImpl<ScmPurchaseMapper, ScmPurchase>
    implements ScmPurchaseService{

    @Autowired
    private ScmPurchaseItemService scmPurchaseItemService;
    @Autowired
    private SysFileHisService sysFileHisService;
    @Autowired
    private FmsAccountsPayService fmsAccountsPayService;
    @Resource
    SysFileHisService fileHisService;
    @Autowired
    private SysApproveNodeRelService sysApproveNodeRelService;
    @Autowired
    private ScmUserApproveRefService scmUserApproveRefService;

    @Autowired
    private ScmApproveHisService scmApproveHisService;
    @Autowired
    private ScmPurchasePlanService scmPurchasePlanService;

    @Override
    public Response<?> addScmPurchase(ScmPurchaseDto scmPurchaseDto) {
        ScmPurchase scmPurchasePlan = new ScmPurchase();
        BeanUtils.copyProperties(scmPurchaseDto,scmPurchasePlan);
        this.save(scmPurchasePlan);
        List<ScmPurchaseItem> itemList = scmPurchaseDto.getItemList();
        scmPurchaseItemService.saveBatch(itemList);
        return Response.succeed();
    }

    @Override
    public Response<?> editScmPurchase(ScmPurchaseDto scmPurchaseDto) {
        ScmPurchase scmPurchase = new ScmPurchase();
        BeanUtils.copyProperties(scmPurchaseDto,scmPurchase);
        this.updateById(scmPurchase);
        LambdaQueryWrapper<ScmPurchaseItem> itemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        itemLambdaQueryWrapper.eq(ScmPurchaseItem::getPurchaseId,scmPurchaseDto.getId());
        scmPurchaseItemService.remove(itemLambdaQueryWrapper);
        List<ScmPurchaseItem> itemList = scmPurchaseDto.getItemList();
        scmPurchaseItemService.saveBatch(itemList);
        return Response.succeed();
    }

    @Override
    public Response<?> del(List<Long> ids) {
        LambdaQueryWrapper<ScmPurchase> scmPurchasePlanWrapper = new LambdaQueryWrapper<>();
        List<ScmPurchase> purchaseDOS = this.listByIds(ids);
        if (ObjectUtil.isEmpty(purchaseDOS)){
            return Response.fail("操作失败");
        }
        List<Integer> idTemps = purchaseDOS.stream().map(ScmPurchase::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ScmPurchaseItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.in(ScmPurchaseItem::getPurchaseId,idTemps);
        this.removeByIds(ids);
        scmPurchaseItemService.remove(itemWrapper);
        return Response.succeed();
    }

    @Override
    public Response<?> findPageListByParam(ScmPurchasePageParam scmPurchasePageParam) {
        //分页
        Page<ScmPurchasePageVo> page = new Page<>(scmPurchasePageParam.getCurrentPage(), scmPurchasePageParam.getPageSize());
        //查询分页
        IPage<ScmPurchasePageVo> pageList = this.baseMapper.findListByParam(page, scmPurchasePageParam);
        if (ObjectUtil.isNotEmpty(pageList.getRecords())){
            pageList.getRecords().forEach(item ->{
                item.setViceNum((ObjectUtil.isEmpty(item.getNeedNum()) || item.getNeedNum().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getMaterialConvCoefficient())) ?
                        BigDecimal.ZERO : item.getNeedNum().multiply(item.getMaterialConvCoefficient()));
                item.setExecutableViceCount((ObjectUtil.isEmpty(item.getExecutableCount()) || item.getExecutableCount().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getMaterialConvCoefficient())) ?
                        BigDecimal.ZERO : item.getExecutableCount().multiply(item.getMaterialConvCoefficient()));
            });
        }

        return Response.succeed(pageList);
    }

    @Override
    public List<FmsAccountsPay> getScmPayById(Integer id) {
        return this.baseMapper.getScmPayById(id);
    }

    @Override
    public ScmPurchaseVo getScmPurchase(Integer id) {
        return this.baseMapper.getScmPurchase(id);
    }

    @Override
    public List<ScmPurchasePageVo> findListByParam(ScmPurchasePageParam scmPurchasePageParam) {
        List<ScmPurchasePageVo> list = this.baseMapper.findListByParam(scmPurchasePageParam);
        list.forEach(item ->{
                item.setViceNum((ObjectUtil.isEmpty(item.getNeedNum()) || item.getNeedNum().equals(BigDecimal.ZERO) || ObjectUtil.isEmpty(item.getMaterialConvCoefficient())) ?
                        BigDecimal.ZERO : item.getNeedNum().divide(item.getMaterialConvCoefficient(),2, BigDecimal.ROUND_HALF_UP));
            });
        return list;
    }




    /**
     * 审批fms_accounts_receivable
     */
    @Override
    public Response<?> approved(Integer id, Integer result, Integer transferId, String desc) {
        // 节点结束： 更新、新增 审批历史记录表-用户关联审批表，
        LambdaQueryWrapper<ScmApproveHis> approveHisWrapper = new LambdaQueryWrapper<>();
        approveHisWrapper.eq(ScmApproveHis::getSourceType, Const.ApproveType.CGJH);
        approveHisWrapper.eq(ScmApproveHis::getSourceId, id);
        approveHisWrapper.orderBy(true,false, ScmApproveHis::getNum);
        approveHisWrapper.last("limit 1");
        ScmApproveHis approveHisDO = scmApproveHisService.getOne(approveHisWrapper);
        long between = DateUtil.between(approveHisDO.getCreateTime(), new Date(), DateUnit.HOUR);
        if (ObjectUtil.isNotEmpty(approveHisDO.getExecutionTimeLimit()) && new Long(approveHisDO.getExecutionTimeLimit()).compareTo(between) < 0){
            Response.fail("超出审批时限：" + approveHisDO.getExecutionTimeLimit() + "小时!");
        }
        LambdaQueryWrapper<ScmUserApproveRef> approveRefWrapper = new LambdaQueryWrapper<>();
        approveRefWrapper.eq(ScmUserApproveRef::getApproveId,approveHisDO.getId());
        approveRefWrapper.eq(ScmUserApproveRef::getDoComplete,0);
        List<ScmUserApproveRef> scmRefList = scmUserApproveRefService.list(approveRefWrapper);
        Map<Integer, ScmUserApproveRef> scmRefListMap = scmRefList.stream().collect(Collectors.toMap(item -> item.getApprovePersonId(), item -> item, (v1, v2) -> v1));
        ScmUserApproveRef scmUserApproveRef = scmRefListMap.get(TokenUtil.getUserId());
        if (ObjectUtil.isEmpty(scmRefList) || ObjectUtil.isEmpty(scmUserApproveRef)){
            Response.fail("审批失败，请联系管理员！");
        }
        return null;
    }

    @Override
    public ScmPurchasePriceVo historyPrice(Integer clientId, Integer materialId) {
        return this.baseMapper.historyPrice(clientId, materialId);
    }

}




